﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
using System.Text.RegularExpressions;

namespace JustPlus
{
    /// <summary>
    /// SearchPanel.xaml 的交互逻辑
    /// </summary>
    public partial class SearchPanel : UserControl
    {
        private string context = "";
        public static string musiciancontext = "";
        public static string albumcontext = "";
        public static string mvurl = "";

        public SearchPanel()
        {
            InitializeComponent();
        }

        private void Grid_MouseLeave(object sender, MouseEventArgs e)
        {
            MainWindow mwnd = (MainWindow)Application.Current.MainWindow;
            mwnd.stackPanel1.Children.Clear();
            mwnd.stackPanel1.Children.Add(mwnd.stackPanel2);
            mwnd.stackPanel1.Children.Add(mwnd.stackPanel3);
        }

        //判断是否可以收听音乐人
        public static bool CanFollowMusician(string musician)
        {
            Parameters parameters = new Parameters();
            parameters.Add("search_text", musician);
            string url = ConnectionBase.ConstructUrlWithParameters("http://music.douban.com/subject_search", parameters);
            string searchresult = new ConnectionBase().Get(url);
            if (string.IsNullOrEmpty(searchresult))
                return false;
            else
            {
                MatchCollection mc = Regex.Matches(searchresult, @"<div class=\""result-item musician\"".*?>.*?</ul>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
                if (mc.Count == 0)
                {
                    return false;
                }
                else
                {
                    string temp = mc[0].Groups[0].Value;
                    MatchCollection tmpmatch = Regex.Matches(temp, @"title=""去FM收听""");
                    if (tmpmatch.Count > 0)
                    {
                        string titleTemp = Regex.Match(temp, @"<a.*?class=\""nbg\"".*?/?>", RegexOptions.IgnoreCase | RegexOptions.Singleline).Groups[0].Value;
                        string link = Regex.Match(titleTemp, @".*?href=\""([^\""]+)\""", RegexOptions.IgnoreCase | RegexOptions.Singleline).Groups[1].Value;
                        musiciancontext = @"channel:0|musician_id:" + link.Substring(33, link.Length - 34);
                        return true;
                    }
                    else
                        return false;
                }
            }
        }

        //判断是否可以收听专辑
        public static bool CanFollowAlbum(string album)
        {
            Parameters parameters = new Parameters();
            parameters.Add("search_text", album);
            string url = ConnectionBase.ConstructUrlWithParameters("http://music.douban.com/subject_search", parameters);
            string searchresult = new ConnectionBase().Get(url);
            if (string.IsNullOrEmpty(searchresult))
                return false;
            else
            {
                MatchCollection mc = Regex.Matches(searchresult, @"<tr.*?class=\""item\"">.*?</tr>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
                if (mc.Count == 0)
                {
                    return false;
                }
                else
                {
                    string temp = mc[0].Groups[0].Value;
                    MatchCollection tmpmatch = Regex.Matches(temp, @"title=""去FM收听""");
                    if (tmpmatch.Count > 0)
                    {
                        string titleTemp = Regex.Match(temp, @"<a.*?class=\""nbg\"".*?/?>", RegexOptions.IgnoreCase | RegexOptions.Singleline).Groups[0].Value;
                        string link = Regex.Match(titleTemp, @".*?href=\""([^\""]+)\""", RegexOptions.IgnoreCase | RegexOptions.Singleline).Groups[1].Value;
                        albumcontext = @"channel:0|subject_id:" + link.Substring(32, link.Length - 33);
                        return true;
                    }
                    else
                        return false;
                }
            }
        }

        //判断是否有MV
        public static bool CanFollowMV(string song,string artist)
        {
            Parameters parameters = new Parameters();
            parameters.Add("searchType", "mv");
            parameters.Add("keyword",song + @" " + artist);
            string url = ConnectionBase.ConstructUrlWithParameters("http://www.yinyuetai.com/search/mv", parameters);
            string searchresult = new ConnectionBase().Get(url);
            if (string.IsNullOrEmpty(searchresult))
                return false;
            else
            {
                MatchCollection mc = Regex.Matches(searchresult, @"<div class=""noResult"">");
                if (mc.Count != 0)
                {
                    return false;
                }
                else
                {
                    MatchCollection mc1 = Regex.Matches(searchresult, @"<div class=""title mv_title"".*?</div>", RegexOptions.Singleline);
                    if (mc1.Count == 0)
                        return false;
                    else
                    {
                        Match tmpmatch = Regex.Match(mc1[0].Groups[0].Value, @"href=""([^\""]+?)""");
                        mvurl = @"http://www.yinyuetai.com/video/player/" + tmpmatch.Groups[1].Value.Substring(7) + @"/v_0.swf";
                        return true;
                    }
                }
            }
        }

        //开始搜索
        public void button1_Click(object sender, RoutedEventArgs e)
        {
            textBlock1.Text = "";
            textBlock2.Text = "";
            textBlock3.Text = "";
            textBlock4.Text = "";
            image1.Source = null;
            ThreadPool.QueueUserWorkItem(new WaitCallback((state) =>
            {
                Dispatcher.Invoke(new Action(() =>
                {
                    Parameters parameters = new Parameters();
                    parameters.Add("search_text", textBox1.Text.Trim());
                    string url = ConnectionBase.ConstructUrlWithParameters("http://music.douban.com/subject_search", parameters);
                    string searchresult = new ConnectionBase().Get(url);
                    if (string.IsNullOrEmpty(searchresult))
                    {
                        textBlock1.Text = "搜索失败，请检查网络或者尝试重新搜索！";
                        return;
                    }
                    //搜索音乐人
                    if ((bool)radioButton1.IsChecked)
                    {
                        MatchCollection mc = Regex.Matches(searchresult, @"<div class=\""result-item musician\"".*?>.*?</ul>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
                        if (mc.Count == 0)
                        {
                            textBlock1.Text = "没有搜索结果或者搜索到的音乐人非豆瓣音乐人，无法收听！";
                            return;
                        }
                        else
                        {
                            string temp = mc[0].Groups[0].Value;
                            string pictureTemp = Regex.Match(temp, @"<img.*?class=\""answer_pic\"".*?/?>", RegexOptions.IgnoreCase | RegexOptions.Singleline).Groups[0].Value;
                            string picture = Regex.Match(pictureTemp, @".*?src=\""([^\""]+)\""", RegexOptions.IgnoreCase | RegexOptions.Singleline).Groups[1].Value;
                            image1.Source = new BitmapImage(new Uri(picture, UriKind.Absolute));

                            string titleTemp = Regex.Match(temp, @"<a.*?class=\""nbg\"".*?/?>", RegexOptions.IgnoreCase | RegexOptions.Singleline).Groups[0].Value;
                            string title = Regex.Match(titleTemp, @".*?title=\""([^\""]+)\""", RegexOptions.IgnoreCase | RegexOptions.Singleline).Groups[1].Value;
                            textBlock1.Text = title;

                            string style = Regex.Match(temp, @"<span>流派</span>([^\""]+?)</li>", RegexOptions.IgnorePatternWhitespace).Groups[1].Value;
                            if (string.IsNullOrEmpty(style))
                                style = "流派：暂无";
                            else
                                style = @"流派" + style.Trim();
                            textBlock2.Text = style;

                            string style0 = Regex.Match(temp, @"<span>风格</span>([^\""]+?)</li>", RegexOptions.IgnorePatternWhitespace).Groups[1].Value;
                            if (string.IsNullOrEmpty(style0))
                                style0 = @"风格：暂无";
                            else
                                style0 = @"风格" + style0.Trim();
                            textBlock3.Text = style0;

                            string albums = Regex.Match(temp, @"<span>热门专辑</span>.*?</li>", RegexOptions.IgnoreCase | RegexOptions.Singleline).Groups[0].Value;
                            MatchCollection hotalbums = Regex.Matches(albums, @"<a href=.*?>([^\""]+)</a>");
                            textBlock4.Text = @"热门专辑：";
                            for (int i = 0; i < hotalbums.Count; i++)
                                textBlock4.Text = textBlock4.Text + hotalbums[i].Groups[1].Value.Replace(@"&amp;",@"&") + @"、";
                            textBlock4.Text = textBlock4.Text.Trim('、');

                            MatchCollection tmpmatch = Regex.Matches(temp, @"title=""去FM收听""");
                            if (tmpmatch.Count>0)
                            {
                                string link = Regex.Match(titleTemp, @".*?href=\""([^\""]+)\""", RegexOptions.IgnoreCase | RegexOptions.Singleline).Groups[1].Value;
                                context = @"channel:0|musician_id:" + link.Substring(33, link.Length - 34);
                                button2.IsEnabled = true;
                                button2.Opacity = 0.6;
                            }
                            else
                            {
                                button2.IsEnabled = false;
                                button2.Opacity = 0.0;
                            }
                        }
                    }
                    else if ((bool)radioButton2.IsChecked)
                    {
                        MatchCollection mc = Regex.Matches(searchresult, @"<tr.*?class=\""item\"">.*?</tr>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
                        if (mc.Count == 0)
                        {
                            textBlock1.Text = "没有搜索结果或者搜索到的专辑版权非豆瓣所有，无法收听！";
                            return;
                        }
                        string temp = mc[0].Groups[0].Value;
                        string pictureTemp = Regex.Match(temp, @"<img.*?/?>", RegexOptions.IgnoreCase | RegexOptions.Singleline).Groups[0].Value;
                        string picture = Regex.Match(pictureTemp, @".*?src=\""([^\""]+)\""", RegexOptions.IgnoreCase | RegexOptions.Singleline).Groups[1].Value;
                        image1.Source = new BitmapImage(new Uri(picture.Replace(@"spic",@"lpic"), UriKind.Absolute));

                        string titleTemp = Regex.Match(temp, @"<a.*?class=\""nbg\"".*?/?>", RegexOptions.IgnoreCase | RegexOptions.Singleline).Groups[0].Value;
                        string title = Regex.Match(titleTemp, @".*?title=\""([^\""]+)\""", RegexOptions.IgnoreCase | RegexOptions.Singleline).Groups[1].Value;
                        textBlock1.Text = title;

                        string album = Regex.Match(temp, @"<p class=""pl"">([^\""]+)</p>").Groups[1].Value;
                        textBlock2.Text = album;

                        MatchCollection tmpmatch = Regex.Matches(temp, @"title=""去FM收听""");
                        if (tmpmatch.Count > 0)
                        {
                            string link = Regex.Match(titleTemp, @".*?href=\""([^\""]+)\""", RegexOptions.IgnoreCase | RegexOptions.Singleline).Groups[1].Value;
                            context = @"channel:0|subject_id:" + link.Substring(32, link.Length - 33);
                            button2.IsEnabled = true;
                            button2.Opacity = 0.6;
                        }
                        else
                        {
                            button2.IsEnabled = false;
                            button2.Opacity = 0.0;
                        }
                        
                    }
                }));
            }));
        }

        //播放搜索到的专辑/音乐人频道
        private void button2_Click(object sender, RoutedEventArgs e)
        {
            GetSongList.currentchannel = new Channel(2, 0, @"搜索音乐");
            //if ((bool)defGeneBox1.Tag)
            {
                GenePanel.context = context;
            }

            MainWindow mwnd = (MainWindow)Application.Current.MainWindow;
            mwnd.stackPanel1.Children.Clear();
            mwnd.stackPanel1.Children.Add(mwnd.stackPanel2);

            PlayerPanel playerpanel = (PlayerPanel)mwnd.stackPanel3.Children[0];
            playerpanel.getsong.Next(true);
        }
    }
}
